import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoollifedemo/business/login/viewmodel/register_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/commonwidget/textfield_widget.dart';
import 'package:schoollifedemo/entity/Entity.dart';
import 'package:schoollifedemo/localization/local_text.dart';

class RegisterPage extends BaseStatefulPage {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _RegisterPageState();
  }
}

class _RegisterPageState extends BasePageState<RegisterPage> {
  final RegisterPageViewModel _viewModel = RegisterPageViewModel();
  bool isCheck = false;

  String _account = '';
  String _password = '';
  String _againPassword = '';
  bool _buttonEnable = false;

  Color _accountDefaultColor = const Color(0xFFB8DCFF);
  Color _passwordDefaultColor = const Color(0xFFB8DCFF);
  Color _againPasswordDefaultColor = const Color(0xFFB8DCFF);

  final Color _errorColor = const Color(0xFFE85252);
  final Color _focusBlueColor = const Color(0xFF529FE8);
  final Color _defaultBlueColor = const Color(0xFFB8DCFF);

  @override
  void initState() {
    _viewModel.init();
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 取消焦点
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          color: Colors.white,
          padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
          child: ListView(
            physics: const BouncingScrollPhysics(),
            children: [
              Column(
                children: [
                  Container(
                    margin: const EdgeInsets.only(top: 50),
                    child: const TextWidget(
                      LoginLocalText.registerTitle,
                      width: 250,
                      height: 60,
                      paddingLeft: 50,
                      paddingRight: 50,
                      paddingTop: 10,
                      paddingBottom: 10,
                      radius: 30,
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 50),
                    child: Stack(
                      children: [
                        const TextWidget(
                          LoginLocalText.account,
                          height: 60,
                          textAxis: MainAxisAlignment.start,
                          fontSize: 16,
                          paddingLeft: 22,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 80),
                          child: TextFieldWidget(
                            width: 200,
                            height: 60,
                            textAlign: TextAlign.center,
                            maxLength: 20,
                            enableCountText: false,
                            insideColor: _accountDefaultColor,
                            onTextChange: (text) {
                              _account = text;
                              _checkButtonEnable();
                              setState(() {});
                            },
                            onFocus: (isFocus) {
                              if (isFocus) {
                                _accountDefaultColor = _focusBlueColor;
                              } else {
                                _accountDefaultColor = _defaultBlueColor;
                              }
                              setState(() {});
                            },
                            formatterList: [
                              FilteringTextInputFormatter(
                                RegExp("[a-zA-Z]"),
                                allow: true,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 30),
                    child: Stack(
                      children: [
                        const TextWidget(
                          LoginLocalText.customPassword,
                          height: 60,
                          textAxis: MainAxisAlignment.start,
                          fontSize: 16,
                          paddingLeft: 22,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 80),
                          child: TextFieldWidget(
                            width: 200,
                            height: 60,
                            textAlign: TextAlign.center,
                            isPassword: true,
                            maxLength: 20,
                            enableCountText: false,
                            insideColor: _passwordDefaultColor,
                            onTextChange: (text) {
                              _password = text;
                              _checkButtonEnable();
                              setState(() {});
                            },
                            onFocus: (isFocus) {
                              if (isFocus) {
                                _passwordDefaultColor = _focusBlueColor;
                              } else {
                                _passwordDefaultColor = _defaultBlueColor;
                              }
                              setState(() {});
                            },
                            formatterList: [
                              FilteringTextInputFormatter(
                                RegExp("[a-zA-Z0-9]"),
                                allow: true,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 30),
                    child: Stack(
                      children: [
                        const TextWidget(
                          LoginLocalText.againPassword,
                          height: 60,
                          textAxis: MainAxisAlignment.start,
                          fontSize: 16,
                          paddingLeft: 22,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 80),
                          child: TextFieldWidget(
                            width: 200,
                            height: 60,
                            textAlign: TextAlign.center,
                            isPassword: true,
                            insideColor: _againPasswordDefaultColor,
                            maxLength: 20,
                            enableCountText: false,
                            onFocus: (isFocus) {
                              if (isFocus) {
                                _againPasswordDefaultColor = _focusBlueColor;
                              } else {
                                _againPasswordDefaultColor = _defaultBlueColor;
                              }
                              setState(() {});
                            },
                            onTextChange: (text) {
                              _againPassword = text;
                              _checkButtonEnable();
                              setState(() {});
                            },
                            formatterList: [
                              FilteringTextInputFormatter(
                                RegExp("[a-zA-Z0-9]"),
                                allow: true,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 50),
                    height: 30,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Checkbox(
                          value: isCheck,
                          onChanged: (changeValue) {
                            isCheck = !isCheck;
                            _checkButtonEnable();
                            setState(() {});
                          },
                          shape: const CircleBorder(),
                        ),
                        Row(
                          children: [
                            const Text(PrivacyLocalText.read),
                            GestureDetector(
                              onTap: () {
                                _viewModel.goToPrivacyPage(context);
                              },
                              child: const Text(
                                PrivacyLocalText.privacyPolicy,
                                style: TextStyle(color: Color(0xFF529FE8)),
                              ),
                            ),
                            const Text(PrivacyLocalText.andClick),
                            const Text(
                              PrivacyLocalText.agree,
                              style: TextStyle(color: Color(0xFF529FE8)),
                            ),
                            const Text(PrivacyLocalText.andContinue),
                          ],
                        ),
                      ],
                    ),
                  ),
                  StreamBuilder(
                    initialData: CommonLoadingState.successTypeOne,
                    stream: _viewModel.registerStateSubject,
                    builder: (builder, spot) {
                      CommonLoadingState? loadingState =
                          spot.data as CommonLoadingState?;
                      switch (loadingState) {
                        case CommonLoadingState.loading:
                          return Container(
                            margin: const EdgeInsets.only(top: 30),
                            width: 80,
                            height: 50,
                            child: const LoadingWidget(),
                          );
                        case CommonLoadingState.successTypeOne:
                          return _rightArrowButton(context);
                        case CommonLoadingState.successTypeTwo:
                          return _rightArrowButton(context);
                        default:
                          return _rightArrowButton(context);
                      }
                    },
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _rightArrowButton(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: ButtonWidget(
        insideWidget: Image.asset('assets/images/common/img_arrow_right.png'),
        width: 80,
        height: 50,
        radius: 50,
        onButtonClick: !_buttonEnable
            ? null
            : () async {
                if (!_checkButtonEnable(isButtonCheck: true)) {
                  setState(() {});
                  return;
                }
                bool? isSave =
                    await _viewModel.checkUserIsSave(account: _account);
                if (isSave == true) {
                  _accountDefaultColor = _errorColor;
                  DialogUtils.showSimpleDialog(
                    context,
                    title: LoginLocalText.error,
                    clickOutSideDismiss: true,
                    widgets: Center(
                      child: TextWidget(
                        LoginLocalText.accountExists,
                        fontSize: 16,
                        textColor: Colors.white,
                        insideColor: _errorColor,
                        textAxis: MainAxisAlignment.center,
                      ),
                    ),
                  );
                  setState(() {});
                } else if (isSave == false) {
                  // 进行注册，注册后返回登录页面
                  await _viewModel.registerAccount(
                    account: _account,
                    password: _password,
                  );
                  _viewModel.backToLoginPage(context);
                } else {
                  // network error
                  DialogUtils.showSimpleDialog(
                    context,
                    title: LoginLocalText.error,
                    clickOutSideDismiss: true,
                    widgets: Center(
                      child: TextWidgetWithOverflow(
                        LoginLocalText.networkErrorOrServerError,
                        fontSize: 16,
                        maxLine: 2,
                        height: 50,
                        textColor: Colors.white,
                        insideColor: _errorColor,
                      ),
                    ),
                  );
                }
              },
      ),
    );
  }

  bool _checkButtonEnable({bool isButtonCheck = false}) {
    if (_account.isEmpty) {
      _buttonEnable = false;
      return false;
    }
    if (_password.isEmpty) {
      _buttonEnable = false;
      return false;
    }
    if (_againPassword.isEmpty) {
      _buttonEnable = false;
      return false;
    }
    if (isButtonCheck) {
      if (_password != _againPassword) {
        _buttonEnable = false;
        _passwordDefaultColor = _errorColor;
        _againPasswordDefaultColor = _errorColor;
        return false;
      }
    }
    if (!isCheck) {
      _buttonEnable = false;
      return false;
    }
    _buttonEnable = true;
    return true;
  }
}
